<template>
    <div class="step_two">
        <div class="reward">
            <div class="reward_left">
                <div class="title">
                    <div class="title_left">奖品设置</div>
                    <div class="title_right">
                        <el-button plain :disabled="status == '2' && type === 'edit'" @click="onAddReward"
                            >添加奖品
                        </el-button>
                    </div>
                </div>
                <el-table
                    id="tableRef"
                    :data="form.reward_info"
                    row-key="id"
                    :header-cell-style="{ background: '#fafafa', color: '#101010', height: '50px' }"
                    stripe>
                    <el-table-column min-width="55">
                        <template #default>
                            <div class="column_height">
                                <div :class="status == '2' && type === 'edit' ? 'can_sort' : 'can_sort try'"></div>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column label="奖品类型" min-width="140">
                        <template #default="{ row }">
                            <div class="column_height">
                                <el-select
                                    v-model="row.reward_type"
                                    :disabled="row.reward_type == 3 || (status == '2' && type === 'edit')">
                                    <el-option
                                        v-for="(item, index) in rewardTypeOptions"
                                        :key="`k${index}`"
                                        :label="item.label"
                                        :value="item.value"></el-option>
                                    <el-option v-if="row.reward_type == 3" label="谢谢参与" :value="3"></el-option>
                                </el-select>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column label="奖品名称" min-width="160">
                        <template #default="{ row }">
                            <div class="column_height">
                                <el-input
                                    v-model="row.reward_title"
                                    placeholder="请输入"
                                    max-length="8"
                                    :disabled="status == '2' && type === 'edit'" />
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column min-width="100">
                        <template #header>
                            <Popover text="奖品图片" content="支持jpg、jpeg、png格式图片" />
                        </template>
                        <template #default="{ row }">
                            <UploadImg
                                :reward-type="row.reward_type"
                                :url="row.reward_image"
                                @submit="url => (row.reward_image = url)">
                            </UploadImg>
                        </template>
                    </el-table-column>
                    <el-table-column min-width="120">
                        <template #header>
                            <Popover text="红包金额" content="金额在0.30-200之间" />
                        </template>
                        <template #default="{ row }">
                            <div class="column_height">
                                <div v-if="row.reward_type == 2" class="red_envelope_money">
                                    <el-input-number
                                        v-model="row.red_envelope_money"
                                        size="small"
                                        :min="0.3"
                                        :max="200"
                                        :precision="2"
                                        :controls="false"
                                        placeholder="0.3~200"
                                        :disabled="status == '2' && type === 'edit'" />
                                    <div>元</div>
                                </div>
                                <div v-else>--</div>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column prop="reward_stock" label="奖品数量" min-width="110">
                        <template #default="{ row }">
                            <div class="column_height">
                                <div v-if="row.reward_type != 3" class="red_envelope_money">
                                    <el-input-number
                                        v-model="row.reward_stock"
                                        size="small"
                                        :min="1"
                                        :controls="false"
                                        placeholder="请输入"
                                        :precision="0"
                                        :disabled="status == '2' && type === 'edit'" />
                                </div>
                                <div v-else>--</div>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column
                        v-if="status == '2' && type === 'edit'"
                        prop="surplus"
                        label="剩余数量"
                        min-width="110">
                        <template #default="{ row }">
                            <div class="column_height">
                                <div v-if="row.reward_type != 3">{{ row.surplus }}</div>
                                <div v-else>--</div>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column label="奖品权重" width="150">
                        <template #default="{ row }">
                            <div class="column_height">
                                <div class="weight_box">
                                    <div class="weight">
                                        <el-input-number
                                            v-model="row.weight"
                                            size="small"
                                            :min="0"
                                            :max="50000000"
                                            :precision="0"
                                            :controls="false"
                                            placeholder="请输入"
                                            @blur="onWeight" />
                                    </div>
                                    <div class="probability">
                                        中奖概率
                                        <span class="probability_num">
                                            {{ onShowProbability(row.reward_probability) }}%
                                        </span>
                                    </div>
                                </div>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" width="200">
                        <template #default="{ row, $index }">
                            <div class="column_height">
                                <div class="btn_box">
                                    <el-button
                                        size="small"
                                        :disabled="status == '2' && type === 'edit'"
                                        @click="onResetReward($index)"
                                        >重置
                                    </el-button>
                                    <el-button
                                        v-if="row.reward_type != 3 && form.reward_info?.length > 2"
                                        size="small"
                                        :disabled="status == '2' && type === 'edit'"
                                        @click="onDelReward($index)"
                                        >删除</el-button
                                    >
                                </div>
                            </div>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
            <div class="reward_right">
                <ActivityPhone :reward-info="form.reward_info" />
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
import Popover from './Popover.vue';
import UploadImg from './UploadImg.vue';
import ActivityPhone from '@/components/zw/phonePreview/activityPhonePreview/luckDraw/index.vue';

import currency from 'currency.js';
import Sortable from 'sortablejs';
import { reactive, nextTick, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { useRoute } from 'vue-router';
const route = useRoute();
const status = route.query.status;
const type = route.query.type;
const form = reactive({
    reward_info: [
        {
            reward_type: 3, // 1-实物 2-红包 3-谢谢参与
            reward_title: '谢谢参与',
            reward_image: 'https://static.scrm.keyid.cn/assets/images/lottery/xiao.png',
            red_envelope_money: 0.3,
            reward_stock: 0,
            weight: 1,
            reward_probability: 10
        },
        {
            reward_type: 1, // 1-实物 2-红包 3-谢谢参与
            reward_title: '',
            reward_image: 'https://static.scrm.keyid.cn/assets/images/lottery/liwu.png',
            red_envelope_money: 0.3,
            reward_stock: 1,
            weight: 1,
            reward_probability: 10
        }
    ]
});
const rewardTypeOptions = [
    { label: '实物奖品', value: 1 },
    { label: '红包奖品', value: 2 }
];
// 保留两位小数
const onShowProbability = (num: any) => num.toString()?.replace(/(\d+\.\d{2})\d+/, '$1');
// 计算奖品权重
const onWeight = () => {
    let weight = 0;
    let weight2 = 0;
    form.reward_info.forEach(item => {
        weight = currency(weight).add(item.weight);
    });
    form.reward_info.forEach(item => {
        // item.reward_probability = item.weight ? currency(item.weight).divide(weight).multiply(100) : 0
        // 原生js计算保留8位小数
        item.reward_probability = item.weight ? ((item.weight / weight) * 100).toFixed(8) : 0;
    });
    form.reward_info.forEach(item => {
        weight2 = currency(weight2).add(item.reward_probability);
    });

    // 除不尽的情况下，多出来的给最后一个
    if (100 - weight2) {
        form.reward_info[form.reward_info.length - 1].reward_probability = currency(
            form.reward_info[form.reward_info.length - 1].reward_probability
        ).add(100 - weight2);
    }
    // 处理权重都是0的情况，谢谢参与概率为100，其他都为0
    if (form.reward_info.every((el: any) => el.weight == 0)) {
        form.reward_info.map((item: any) => {
            if (item.reward_type == 3) {
                item.reward_probability = currency(0).add(100);
            } else {
                item.reward_probability = 0;
            }
        });
    }
    let weight3 = 0;
    form.reward_info.forEach(item => {
        weight3 = currency(weight3).add(item.reward_probability).value;
    });
};
// 添加奖品
const onAddReward = () => {
    if (form.reward_info.length == 8) {
        ElMessage.warning('最多添加8个奖品');
        return;
    }
    form.reward_info.push({
        reward_type: 1, // 1-实物 2-红包 3-谢谢参与
        reward_title: '',
        reward_image: 'https://static.scrm.keyid.cn/assets/images/lottery/liwu.png',
        red_envelope_money: 0.3,
        reward_stock: 1,
        weight: 1,
        reward_probability: 10
    });
    onWeight();
};

// 删除奖品
const onDelReward = (index: number) => {
    form.reward_info.splice(index, 1);
    onWeight();
};
// 重置奖品
const onResetReward = (index: number) => {
    // form.reward_info[index].reward_type = 1
    form.reward_info[index].reward_title = '';
    form.reward_info[index].reward_image = '';
    form.reward_info[index].red_envelope_money = 0.3;
    form.reward_info[index].reward_stock = 1;
    form.reward_info[index].sort = 1;
    form.reward_info[index].weight = 1;
    form.reward_info[index].reward_probability = 0;
    onWeight();
};

// 拖拽
const setSortableFun = () => {
    let copyTableList: any;
    let nowIndex: any;
    nextTick(() => {
        const el = document.querySelector('#tableRef .el-table__body-wrapper  tbody');
        const SortableBox = new Sortable(el, {
            animation: 100,
            sort: true,
            delay: 0,
            delayOnTouchOnly: false,
            handle: '.try',
            filter: '.no-sort',
            onChoose: function (evt: any) {
                nowIndex = evt.oldIndex;
            },
            onMove: function (evt: any, originalEvent: any) {
                // console.log('移动中', evt)
                // let index = evt.related.querySelector('.table-item').getAttribute('data-id')
                // if (index == 0 || index == reward_info.stages.length - 1 || index == reward_info.stages.length - 2) {
                //   return false
                // }
                // return true
            },
            //
            onEnd: (evt: any) => {
                // console.log(evt, '----------------');
                // console.log(evt.oldIndex, '元素在旧父级中的旧索引');
                // console.log(evt.newIndex, '元素在新父级中的新索引');
                // console.log(evt.oldDraggableIndex, '元素在旧父级中的旧索引，仅计数可拖动的元素');
                // console.log(evt.newDraggableIndex, '元素在新父级中的新索引，仅计数可拖动元素');
                copyTableList = JSON.parse(JSON.stringify(form.reward_info));
                const data = copyTableList.splice(evt.oldIndex, 1)[0];
                copyTableList.splice(evt.newIndex, 0, data);
                let next_id, pre_id;
                if (copyTableList[evt.newIndex - 1]) {
                    pre_id = copyTableList[evt.newIndex - 1].source_id;
                }
                if (copyTableList[evt.newIndex + 1]) {
                    next_id = copyTableList[evt.newIndex + 1].source_id;
                }
                const arr: any = [];
                copyTableList.forEach((item: any, index: number) => {
                    arr.push({ id: item.id, sort: index + 1 });
                });
                form.reward_info = [];
                nextTick(() => {
                    form.reward_info = copyTableList;
                });
            }
        });
    });
};

// 兜底校验
const validate = () => {
    return new Promise((resolve, reject) => {
        for (let i = 0; i < form.reward_info.length; i++) {
            if (!form.reward_info[i].reward_title) {
                ElMessage.warning('请填写奖品名称');
                return;
            }
            if ([1, 2].includes(form.reward_info[i].reward_type)) {
                if (!form.reward_info[i].reward_image) {
                    ElMessage.warning('请上传奖品图片');
                    return;
                }
            }
            if (form.reward_info[i].reward_type == 2) {
                if (!form.reward_info[i].red_envelope_money) {
                    ElMessage.warning('请填写红包金额');
                    return;
                }
            }
            if (!form.reward_info[i].reward_stock && form.reward_info[i].reward_type != 3) {
                ElMessage.warning('请填写奖品库存');
                return;
            }
        }
        // 奖品名称不能重复
        const arr = form.reward_info.map((item: any) => {
            return item.reward_title;
        });
        const newArr = [...new Set(arr)];
        if (arr.length != newArr.length) {
            ElMessage.warning('奖品名称不能重复');
            return;
        }
        resolve(true);
    });
};

onMounted(() => {
    onWeight();
    setSortableFun();
});

defineExpose({
    form,
    validate,
    onWeight
});
</script>

<style scoped lang="scss">
.step_two {
    // width: 1050px;

    .title {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 16px;
        font-size: 16px;
        font-weight: 500;
        color: #33302d;

        .title_left {
            &::before {
                content: '';
                display: inline-block;
                width: 4px;
                height: 16px;
                background: #ff6b00;
                margin-right: 6px;
                vertical-align: top;
            }
        }

        .title_right {
        }
    }

    .reward {
        display: flex;
        justify-content: space-between;

        .reward_left {
            flex: 1;
            overflow-x: auto;
        }

        .reward_right {
            display: flex;
            justify-content: center;
            width: 400px;
            margin-left: 50px;
        }
    }
}

.column_height {
    height: 50px;

    .btn_box {
        display: flex;

        div {
            display: grid;
            place-items: center;
            padding: 0 10px;
            background: #fff;
            border-radius: 2px;
            border: 1px solid #eaeaea;
            cursor: pointer;
            font-size: 12px;

            &:hover {
                color: #ff6b00;
            }
        }

        .btn_reset {
            margin-right: 10px;
        }
    }

    .can_sort {
        width: 20px;
        height: 48px;
        background: url('@/assets/customer/sort-icon.png') no-repeat;
        background-size: 100%;
        background-position-y: 7px;
    }

    .btn {
        padding: 0 10px;
        max-height: 28px !important;
        border: 1px solid #eaeaea;
        border-radius: 2px;
        text-align: center;
        background: #fff;
    }

    .red_envelope_money {
        display: flex;
        align-items: center;

        .el-input-number {
            margin-right: 4px;
        }
    }

    .weight_box {
        // padding-top: 20px;

        .weight {
            display: flex;
        }
    }

    .probability {
        display: flex;
        width: 100%;
        padding-top: 4px;
        line-height: 1;

        .probability_num {
            color: #ff6b00;
        }
    }
}
</style>
